﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace AIC_CD
{
    public partial class BaoCaoThucHienChuongTrinh1TyDong_Update : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            CheckPermission();
            if (!IsPostBack)
            {
                Config();
                BindDataToControls();
            }
        }

        private void Config()
        {
            ContentPlaceHolder MainContent = this.Page.Master.FindControl("MainContent") as ContentPlaceHolder;
            for (int i = 3; i <= 15; i++)
            {
                string ControlName = "TextBox" + (i - 2);
                TextBox txtField = (TextBox)MainContent.FindControl(ControlName);
                txtField.Text = "";
            }
        }

        private void CheckPermission()
        {
            Dictionary<string, int> Role = MyCommon.CheckPermission("KetQuaThucHienCongTac1TyDong");
            if (Role == null || Role["Xem"] == 0 || ((Role["Xem"] == 1 && Role["Sua"] == 0)))
            {
                Response.Redirect("Index.aspx?p=0");
            }
        }

        protected void btnLuu_Click(object sender, EventArgs e)
        {
            String sql = "SELECT * FROM dbo.tblBaoCaoKetQuaThucHienChuongTrinh1TyDong WHERE KyBaoCaoID_DM = @KyBaoCaoID_DM AND DonViID = @DonViID";
            List<SqlParameter> lstParameters = new List<SqlParameter>();
            lstParameters.Add(SqlHelper.CreateParameterObject("@KyBaoCaoID_DM", SqlDbType.Int, ParameterDirection.Input, cboKyBaoCao.SelectedValue));
            lstParameters.Add(SqlHelper.CreateParameterObject("@DonViID", SqlDbType.Int, ParameterDirection.Input, MyCommon.GetDonViID(Session["userid"].ToString())));

            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql, lstParameters);
            if (dt.Rows.Count == 0)
            {
                btnLuu.CommandName = MyConst.Action.Addnew;
            }
            else
            {
                btnLuu.CommandName = MyConst.Action.Update;
            }
            string fieldBuilder = "";
            string paramBuilder = "";
            string updateBuilder = "";
            for (int i = 1; i <= 13; i++)
            {
                fieldBuilder += "F" + i + ",";
                paramBuilder += "@F" + i + ",";
                updateBuilder += "F" + i + "=@F" + i + ",";
            }

            if (btnLuu.CommandName == MyConst.Action.Addnew)
            {
                string sSQL = "INSERT INTO dbo.tblBaoCaoKetQuaThucHienChuongTrinh1TyDong( KyBaoCaoID_DM ,DonViID, SoBaoCao ," + fieldBuilder +
                              "CM_ThoiGianBaoCao ,CM_TenBaoCao ,CM_NguoiTongHop, CM_ThuTruong, CreateDate ,UpdateDate ,UserID) " +
                              "VALUES (@KyBaoCaoID_DM,@DonViID,@SoBaoCao," + paramBuilder +
                              "GETDATE(),@CM_TenBaoCao,@CM_NguoiTongHop, @CM_ThuTruong,GETDATE(),GETDATE(),@UserID)";

                List<SqlParameter> lstParameter = new List<SqlParameter>();
                lstParameter.Add(SqlHelper.CreateParameterObject("@KyBaoCaoID_DM", SqlDbType.Int, ParameterDirection.Input, cboKyBaoCao.SelectedValue));
                lstParameter.Add(SqlHelper.CreateParameterObject("@DonViID", SqlDbType.Int, ParameterDirection.Input, MyCommon.GetDonViID(Session["userid"].ToString())));
                lstParameter.Add(SqlHelper.CreateParameterObject("@SoBaoCao", SqlDbType.NVarChar, ParameterDirection.Input, txtSoBaoCao.Text.Trim()));
                ContentPlaceHolder MainContent = this.Page.Master.FindControl("MainContent") as ContentPlaceHolder;
                for (int i = 3; i <= 15; i++)
                {
                    if (i == 15)
                    {
                        lstParameter.Add(SqlHelper.CreateParameterObject("@F13", SqlDbType.NVarChar, ParameterDirection.Input, TextBox13.Text.Trim()));
                    }
                    else
                    {
                        string ControlName = "TextBox" + (i - 2);
                        TextBox txtField = (TextBox)MainContent.FindControl(ControlName);
                        lstParameter.Add(SqlHelper.CreateParameterObject("@F" + (i - 2), SqlDbType.Float, ParameterDirection.Input, txtField.Text.Trim().Equals("") ? "0" : txtField.Text.Trim()));
                    }
                }
                lstParameter.Add(SqlHelper.CreateParameterObject("@CM_TenBaoCao", SqlDbType.NVarChar, ParameterDirection.Input, txtTenBaoCao.Text.Trim().Equals("") ? " " : txtTenBaoCao.Text.Trim()));
                lstParameter.Add(SqlHelper.CreateParameterObject("@CM_NguoiTongHop", SqlDbType.NVarChar, ParameterDirection.Input, txtNguoiTongHop.Text.Trim().Equals("") ? " " : txtNguoiTongHop.Text.Trim()));
                lstParameter.Add(SqlHelper.CreateParameterObject("@CM_ThuTruong", SqlDbType.NVarChar, ParameterDirection.Input, txtThuTruong.Text.Trim().Equals("") ? " " : txtThuTruong.Text.Trim()));
                lstParameter.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, Convert.ToInt32(Session["userid"])));

                SqlHelper.ExecuteNonQuery(CommandType.Text, sSQL, lstParameter);
                MyCommon.AddMessage(this.Page.Master, "Thêm mới báo cáo thành công", MyConst.MessageType.Success);
            }
            else
            {
                string sSQL = "Update tblBaoCaoKetQuaThucHienChuongTrinh1TyDong Set CM_TenBaoCao=@CM_TenBaoCao,SoBaoCao = @SoBaoCao, " + updateBuilder + "CM_NguoiTongHop = @CM_NguoiTongHop, CM_ThuTruong= @CM_ThuTruong,UpdateDate = GETDATE(),UserID = @UserID " +
                                "Where DonViID=" + MyCommon.GetDonViID(Session["userid"].ToString()) + " And KyBaoCaoID_DM=" + cboKyBaoCao.SelectedValue;

                List<SqlParameter> lstParameter = new List<SqlParameter>();
                lstParameter.Add(SqlHelper.CreateParameterObject("@CM_TenBaoCao", SqlDbType.NVarChar, ParameterDirection.Input, txtTenBaoCao.Text.Trim().Equals("") ? " " : txtTenBaoCao.Text.Trim()));
                lstParameter.Add(SqlHelper.CreateParameterObject("@SoBaoCao", SqlDbType.NVarChar, ParameterDirection.Input, txtSoBaoCao.Text.Trim().Equals("") ? " " : txtSoBaoCao.Text.Trim()));
                lstParameter.Add(SqlHelper.CreateParameterObject("@CM_NguoiTongHop", SqlDbType.NVarChar, ParameterDirection.Input, txtNguoiTongHop.Text.Trim().Equals("") ? " " : txtNguoiTongHop.Text.Trim()));
                lstParameter.Add(SqlHelper.CreateParameterObject("@CM_ThuTruong", SqlDbType.NVarChar, ParameterDirection.Input, txtThuTruong.Text.Trim().Equals("") ? " " : txtThuTruong.Text.Trim()));
                ContentPlaceHolder MainContent = this.Page.Master.FindControl("MainContent") as ContentPlaceHolder;
                for (int i = 3; i <= 15; i++)
                {
                    if (i == 15)
                    {
                        lstParameter.Add(SqlHelper.CreateParameterObject("@F13", SqlDbType.NVarChar, ParameterDirection.Input, TextBox13.Text.Trim()));
                    }
                    else
                    {
                        string ControlName = "TextBox" + (i - 2);
                        TextBox txtField = (TextBox)MainContent.FindControl(ControlName);
                        lstParameter.Add(SqlHelper.CreateParameterObject("@F" + (i - 2), SqlDbType.Float, ParameterDirection.Input, txtField.Text.Trim().Equals("") ? "0" : txtField.Text.Trim()));
                    }
                }
                lstParameter.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, Session["userid"]));


                SqlHelper.ExecuteNonQuery(CommandType.Text, sSQL, lstParameter);

                MyCommon.AddMessage(this.Page.Master, "Lưu thông tin báo cáo thành công", MyConst.MessageType.Success);
            }
        }

        protected void cboKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboKyBaoCao.SelectedValue != "0")
            {
                btnLuu.Visible = true;
                BaoCaoDinhKem.Visible = true;
                BindDataToBaoCao();
            }
            else
            {
                btnLuu.Visible = false;
                BaoCaoDinhKem.Visible = false;
            }
        }

        private void BindDataToBaoCao()
        {
            string sql = "SELECT * FROM dbo.tblBaoCaoKetQuaThucHienChuongTrinh1TyDong WHERE KyBaoCaoID_DM = @KyBaoCaoID_DM AND DonViID = @DonViID";
            List<SqlParameter> lstParameters = new List<SqlParameter>();
            lstParameters.Add(SqlHelper.CreateParameterObject("@KyBaoCaoID_DM", SqlDbType.Int, ParameterDirection.Input, cboKyBaoCao.SelectedValue));
            lstParameters.Add(SqlHelper.CreateParameterObject("@DonViID", SqlDbType.Int, ParameterDirection.Input, MyCommon.GetDonViID(Session["userid"].ToString())));

            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql, lstParameters);
            if (dt.Rows.Count != 0)
            {
                btnLuu.Text = "Cập nhật báo cáo";
                btnLuu.CommandName = MyConst.Action.Update;
                BindDataToTextField(dt);
            }
            else
            {
                Config();
                btnLuu.Text = "Thêm mới báo cáo";
                btnLuu.CommandName = MyConst.Action.Addnew;
            }
        }

        private void BindDataToTextField(DataTable dt)
        {
            ContentPlaceHolder MainContent = this.Page.Master.FindControl("MainContent") as ContentPlaceHolder;
            for (int i = 3; i <= 15; i++)
            {
                string ControlName = "TextBox" + (i - 2);
                TextBox txtField = (TextBox)MainContent.FindControl(ControlName);
                txtField.Text = dt.Rows[0][i+1].ToString();
            }
            txtSoBaoCao.Text = dt.Rows[0]["SoBaoCao"].ToString();
            txtNguoiTongHop.Text = dt.Rows[0]["CM_NguoiTongHop"].ToString();
            txtThuTruong.Text = dt.Rows[0]["CM_ThuTruong"].ToString();
        }

        /// <summary>
        /// Bind Data vào các contrls như Combobox, ListBox, textBox ...
        /// </summary>
        private void BindDataToControls()
        {
            //TODO
            if (Session["userid"] != null)
            {

                string sql = "Select DV.* " +
                             "From tblDonVi DV " +
                             "Inner Join tblUser U On U.DonViID=DV.ID " +
                             "Where U.ID=" + Session["userid"];
                DataTable dtDV = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
                lblDonVi.Text = "(" + dtDV.Rows[0]["MaDV"] + ") " + dtDV.Rows[0]["TenDV"];

                sql = "Select ID,TenDM From tblDanhMuc Where MaDM='" + MyConst.DanhMuc.KyBaoCao.Ma + "' ";
                SqlDataReader reKyBaoCao = SqlHelper.ExecuteReader(CommandType.Text, sql);
                clsDataBind.CreateCombo("Tất cả", reKyBaoCao, cboKyBaoCao, 1, 0);
            }
        }
    }
}
